using System;
using System.Collections;
using System.Text;
using System.Management;

namespace Niu
{
    public class nIP
    {
        private String m_IP = "";
        private String m_Mask = "";

        public nIP(String IP, String Mask)
        {
            m_IP = IP;
            m_Mask = Mask;
        }

        public nIP(String IP) : this(IP, "255.255.255.255")
        {

        }

        public nIP() : this("0.0.0.0")
        {

        }

        public String IP
        {
            get
            {
                return m_IP;
            }
            set
            {
                m_IP = value;
            }
        }

        public String Mask
        {
            get
            {
                return m_Mask;
            }
            set
            {
                m_Mask = value;
            }
        }

        public static Boolean IsIP(String IP)
        {
            String ip = IP.Trim();

            String[] nums = ip.Split(new Char[] { '.' });

            if (nums.Length != 4)
            {
                return false;
            }

            Int32 num = 0;
            foreach (String tmp in nums)
            {
                if (Int32.TryParse(tmp, out num) == false)
                {
                    return false;
                }

                if (num > 255 || num < 0)
                {
                    return false;
                }
            }

            return true;
        }
    }

    public class nIPAdapter
    {
        /*********************************************************************************
         * ManagementBaseObject["returnValue"] 
         * 
         * 0 Successful completion, no reboot required.
         * 1 Successful completion, reboot required.
         * 64 Method not supported on this platform.
         * 65 Unknown failure.
         * 66 Invalid subnet mask.
         * 67 An error occurred while processing an instance that was returned.
         * 68 Invalid input parameter.
         * 69 More than five gateways specified.
         * 70 Invalid IP address.
         * 71 Invalid gateway IP address.
         * 72 An error occurred while accessing the registry for the requested information.
         * 73 Invalid domain name.
         * 74 Invalid host name.
         * 75 No primary or secondary WINS server defined.
         * 76 Invalid file.
         * 77 Invalid system path.
         * 78 File copy failed.
         * 79 Invalid security parameter.
         * 80 Unable to configure TCP/IP service.
         * 81 Unable to configure DHCP service.
         * 82 Unable to renew DHCP lease.
         * 83 Unable to release DHCP lease.
         * 84 IP not enabled on adapter.
         * 85 IPX not enabled on adapter.
         * 86 Frame or network number bounds error.
         * 87 Invalid frame type.
         * 88 Invalid network number.
         * 89 Duplicate network number.
         * 90 Parameter out of bounds.
         * 91 Access denied.
         * 92 Out of memory.
         * 93 Already exists.
         * 94 Path, file, or object not found.
         * 95 Unable to notify service.
         * 96 Unable to notify DNS service.
         * 97 Interface not configurable.
         * 98 Not all DHCP leases could be released or renewed.
         * 100 DHCP not enabled on adapter.
         **********************************************************************************/

        private ManagementObject m_MO = null;

        internal nIPAdapter(ManagementObject mo)
        {
            m_MO = mo;
        }

        public String GetName()
        {
            return m_MO["Description"].ToString();
        }
        public String GetMAC()
        {
            return m_MO["MACAddress"].ToString();
        }
        public String GetID()
        {
            return m_MO["SettingID"].ToString();
        }

        public Boolean GetDHCP()
        {
            return (Boolean)m_MO["DHCPEnabled"];
        }
        public void SetDHCP()
        {
            m_MO.InvokeMethod("EnableDHCP", null);
        }

        public nIP[] GetIP()
        {
            ArrayList items = new ArrayList();

            String[] ips = (String[])m_MO["IPAddress"];
            String[] masks = (String[])m_MO["IPSubnet"];

            Int32 count = ips.Length <= masks.Length ? ips.Length : masks.Length;

            for (int i = 0; i < count; i++)
            {
                items.Add(new nIP(ips[i], masks[i]));
            }

            return (nIP[])items.ToArray(typeof(nIP));

        }
        public Boolean SetIP(String[] IPs, String[] Masks)
        {
            ManagementBaseObject mbo = null;

            try
            {
                if (IPs.Length != Masks.Length)
                {
                    return false;
                }

                mbo = m_MO.GetMethodParameters("EnableStatic");
                mbo["IPAddress"] = IPs;
                mbo["SubnetMask"] = Masks;
                mbo = m_MO.InvokeMethod("EnableStatic", mbo, null);

                if ((Int32)mbo["returnValue"] != 0)
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
        public Boolean SetIP(String IP, String Mask)
        {
            return SetIP(new String[] { IP }, new String[] { Mask });
        }
        public Boolean SetIP(nIP[] IPs)
        {
            String[] ips = new String[IPs.Length];
            String[] masks = new String[IPs.Length];

            for (Int32 i = 0; i < IPs.Length; i++)
            {
                ips[i] = IPs[i].IP;
                masks[i] = IPs[i].Mask;
            }

            return SetIP(ips, masks);
        }

        public String[] GetGateway()
        {
            if (m_MO["DefaultIPGateway"] == null)
            {
                return new String[0];
            }
            else
            {
                return (String[])m_MO["DefaultIPGateway"];
            }
        }
        public Boolean SetGateway(String[] Gateway)
        {
            ManagementBaseObject mbo = null;

            try
            {
                mbo = m_MO.GetMethodParameters("SetGateways");
                mbo["DefaultIPGateway"] = Gateway;
                mbo = m_MO.InvokeMethod("SetGateways", mbo, null);
                if ((Int32)mbo["returnValue"] != 0)
                {
                    return false;
                }

            }
            catch
            {
                return false;
            }

            return true;
        }
        public Boolean SetGateway(String Gateway)
        {
            return SetGateway(new String[] { Gateway });
        }

        public String[] GetDNS()
        {
            if (m_MO["DNSServerSearchOrder"] == null)
            {
                return new String[0];
            }
            else
            {
                return (String[])m_MO["DNSServerSearchOrder"];
            }
        }
        public Boolean SetDNS(String[] DNS)
        {
            ManagementBaseObject mbo = null;

            try
            {
                mbo = m_MO.GetMethodParameters("SetDNSServerSearchOrder");
                mbo["DNSServerSearchOrder"] = DNS;
                mbo = m_MO.InvokeMethod("SetDNSServerSearchOrder", mbo, null);
                if ((Int32)mbo["returnValue"] != 0)
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
        public Boolean SetDNS(String DNS1, String DNS2)
        {
            return SetDNS(new String[] { DNS1, DNS2 });
        }
        public Boolean SetDNS(String DNS)
        {
            return SetDNS(new String[] { DNS });

        }
        public Boolean SetDNS()
        {
            return SetDNS((String[])null);

        }
    }

    public static class nIPAdapters
    {
        public static nIPAdapter[] GetAll()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            ArrayList items = new ArrayList();

            foreach (ManagementObject mo in moc)
            {
                if ((Boolean)mo["IPEnabled"] == true)
                {
                    items.Add(new nIPAdapter(mo));
                }
            }

            return (nIPAdapter[]) items.ToArray(typeof(nIPAdapter));
        }

    }
}
